﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Beetle.Web.Extensions
{
    public static class DataPanelExtension
    {
        /// <summary>
        /// 自动读取双向绑定元素，生成指定的实体。
        /// </summary>
        /// <typeparam name="T">返回实体的类型</typeparam>
        /// <param name="dataPanel"></param>
        /// <returns></returns>
        public static T Parser<T>(this Beetle.Web.UI.WebControls.DataPanel dataPanel) where T : class, new()
        {
            T t = new T();
            dataPanel.Parser<T>(t);
            return t;
        }

        /// <summary>
        /// 自动读取双向绑定元素，更新指定的实体。
        /// </summary>
        /// <typeparam name="T">更新指定的实体的类型</typeparam>
        /// <param name="dataPanel"></param>
        /// <param name="entity">要更新的实体</param>
        public static void Parser<T>(this Beetle.Web.UI.WebControls.DataPanel dataPanel, T entity) where T : class, new()
        {
            System.Collections.Specialized.IOrderedDictionary dict = dataPanel.ExtractValues();

            if (dict == null || dict.Count == 0)
            {
                return;
            }

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            Type tType = typeof(T);

            foreach (System.Collections.DictionaryEntry entry in dict)
            {
                System.Reflection.PropertyInfo property = tType.GetProperty(entry.Key.ToString());

                if (property != null)
                {
                    try
                    {
                        Type propertyType = property.PropertyType;

                        if (propertyType.FullName.IndexOf("System.Nullable") == 0)
                        {
                            propertyType = System.Nullable.GetUnderlyingType(propertyType);
                        }

                        property.SetValue(entity, Convert.ChangeType(entry.Value, propertyType), null);
                    }
                    catch { }
                }
            }
        }
    }
}
